<template>
  <div class="footer-send-input">
    <Editor
      mode="simple"
      style="height: 100%; width: 100%; overflow-y: hidden"
      :defaultConfig="editorConfig"
      v-model="html"
      @onChange="onChange"
      @onCreated="onCreated"
      @customPaste="customPaste"
    />
    <div class="send-btn">
      <div class="explain-text">{{$t('im.imChat.components.messageBox.inputEdit.des1')}}</div>
      <el-button
        type="primary"
        :disabled="disabled || isEmpty"
        :loading="pending"
        @click="onSendMsg"
        >{{$t('common.base.send')}}</el-button
      >
    </div>
  </div>
</template>

<script>
/** vue */
import EventBus from '@src/util/eventBus';

/** components */
import { Editor } from '@wangeditor/editor-for-vue';
import { DomEditor } from '@wangeditor/editor';
/** util */
import {
  getCustomPasteValue,
  uploadFile,
  isImageNode,
  checkValIsEmpty,
  getMessageType,
  flatten,
} from 'src/modules/im/imChat/components/messageBox/inputEdit/util.js';
import { emojiNames } from '@src/modules/im/imChat/utils/tools.js';
import { customerServiceSendNewMessage } from '@src/modules/im/imChat/components/messageBox/send.js';
import i18n from '@src/locales'
import { difference } from 'lodash';
import { deleteServerFiles } from 'pub-bbx-utils';
export default {
  name: 'input-edit',
  components: {
    Editor,
    DomEditor,
  },
  props: {
    hxIdObj: {
      type: Object,
      default: () => {},
    },
    disabled: {
      type: Boolean,
      default: true,
    },
    source: {
      type: String,
    },
  },
  computed: {
    isWeChat() {
      return this.source == 'weChat';
    },
  },
  data() {
    return {
      editor: null,
      html: ``,
      isEmpty: true,
      pending: false,
      editorConfig: {
        placeholder: i18n.t('im.imChat.components.messageBox.inputEdit.pla1'),
        pasteFilterStyle: false,
        selection: null,
        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
          uploadImage: {
            customBrowseAndUpload() {
              // 自定义上传图片
            },
          },
        },
        hoverbarKeys: {
          link: {
            menuKeys: [],
          },
          text: {
            menuKeys: [],
          },
          image: {
            menuKeys: [],
          },
        },
      },
      oldContent: {
        oldImages: [],
      },
      canDelete: true,
    };
  },
  created() {
    EventBus.$on('setHtml', this.setHtml);
    EventBus.$on('setIsEmpty', this.setIsEmptyHandler);
    EventBus.$on('sendMsg', this.onSendMsg);
    // this.setPlaceholder();
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
      if (this.disabled) this.editor.disable();
      const { $textArea } = DomEditor.getTextarea(editor);

      //监听shift+ctrl按键
      if ($textArea) {
        $textArea.on('keydown', event => {
          if (event.key === 'Enter' && event.ctrlKey) {
            this.dangerouslyInsertHtml('<span><br /></span>');
            event.preventDefault();
          }
        });

        //监听Enter按键
        $textArea.on('keypress', event => {
          if (event.key === 'Enter') {
            this.onSendMsg();
            event.preventDefault();
          }
        });

        //监听双击事件
        $textArea.on('dblclick', event => {
          let target = event.target;
          if (isImageNode(target)) {
            let dataHref = target.getAttribute('data-href');
            dataHref = dataHref ? JSON.parse(dataHref) : dataHref;
            if (dataHref?.isemoji) return;
            this.$previewElementImg(target.currentSrc);
            event.preventDefault();
          }
        });

        //监听删除按键
        $textArea.on('keypress', event => {
          if (event.keyCode == 8 || event.keyCode == 46) {
            setTimeout(() => {
              // 解决连续多张图片排列，删除后面一张图片会默认选中前面一张图片的问题
              this.editor.move(1);
            });
          }
        });
      }
    },

    onChange(editor) {
      this.isEmpty = checkValIsEmpty(editor.children);
      this.diffContent()
    },

    //粘贴事件
    async customPaste(editor, e,callBack) {
      e.preventDefault()
      callBack(false)
      let res = getCustomPasteValue(e);
      if (!res) return;

      if (res.type == 'text') {
        this.insertText(res.value);
      } else if (
        res.type == 'file' &&
        res.fileType == 'image') {
        const fileInfo = await uploadFile(res.value);
        if (!fileInfo) return;
        const { fileName, id, ossUrl, size } = fileInfo;
        this.dangerouslyInsertHtml(`<img src="${ossUrl}" alt="${id}"/>`);
      }
    },

    async onSendMsg() {
      if (this.isEmpty) return;
      if (this.pending) return;

      this.editor.disable();
      this.pending = true;

      try {
        let messageType = '';
        messageType = getMessageType(this.editor.children);
        const params = {
          conversationId: this.hxIdObj.conversationId,
          messageType: messageType,
          messageContent: {},
        };

        if (messageType == 'txt') {
          params.messageContent = {
            msg: this.editor.getText().replace(/^\s+|\s+$/g, ''),
          };
        } else if (messageType == 'newImage') {
          let url = flatten(this.editor.children).find(
            v => v.type == 'image'
          ).src;
          params.messageContent = {
            type: 'custom',
            customEvent: messageType,
            customExts: {
              url,
              filename:'在线客服图片.png'
            },
          };
        } else if (messageType == 'paragraph') {
          if(this.isWeChat) return this.$message.warning(this.$t('im.imChat.components.messageBox.inputEdit.tips1'))
          params.messageContent = {
            type: 'custom',
            customEvent: messageType,
            customExts: {
              msg: this.editor.getHtml(),
              nodes: this.editor.children,
            },
          };
        }

        const messageInfo = await customerServiceSendNewMessage(params);
        EventBus.$emit('addMessageByKF', messageInfo);
        // 发送消息不删除
        this.canDelete = false
        this.editor.clear();
      } catch (err) {
        console.log(err);
      } finally {
        this.pending = false;
        this.editor.enable();
        setTimeout(() => {
          this.getFocus();
        });
      }
    },
    insertText(val) {
      this.editor.insertText(val);
    },
    setIsEmptyHandler(val) {
      this.isEmpty = val;
    },
    setHtml(val) {
      this.editor.setHtml(val);
    },

    dangerouslyInsertHtml(val) {
      this.editor.dangerouslyInsertHtml(val);
    },

    getFocus() {
      this.editor.focus();
    },

    setEmoji(txt) {
      // let emojiImg = this.emotion(txt);
      // this.dangerouslyInsertHtml(emojiImg);
      // 表情包不按图片处理
      this.insertText(txt)
    },
    // 将匹配结果替换表情图片
    emotion(res) {
      if (this.isWeChat) return res;

      let word = res.replace(/\[|\]/gi, '');
      let index = emojiNames.indexOf(word);
      if (~index) {
        let obj = JSON.stringify({ isemoji: true });
        return `<img src="/resource/images/emoji/${index}.gif" data-href=${obj}>`;
      }
      return word;
    },
    setPlaceholder() {
      this.editorConfig.placeholder = this.isWeChat
        ? this.$t('im.imChat.components.messageBox.inputEdit.pla2')
        : this.$t('im.imChat.components.messageBox.inputEdit.pla3');
    },
    // 比较内容
    diffContent() {
      try {
        const { oldImages } = this.oldContent
        const images = this.editor.getElemsByType('image')

        // 比较图片，判断是否有被删除
        {
          const diffImagesIds = difference(oldImages.map(v=>v.alt), images.map(v=>v.alt))
          if (diffImagesIds.length && this.canDelete) {
            deleteServerFiles(diffImagesIds)
          } else {
            this.canDelete = true
          }
        }
        
        // 更新旧值
        this.oldContent = {
          oldImages: images
        }
      } catch (error) {
        console.log(error)
      }
    },
  },
  beforeDestroy() {
    EventBus.$off('setHtml');

    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁 editor ，重要！！！
  },
};
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
::v-deep .w-e-text-placeholder {
  top: 6px !important;
  left: 5px !important;
  font-style: inherit !important;
}
::v-deep .w-e-text-container [data-slate-editor] {
  padding: 0 !important;
}
::v-deep .w-e-text-container [data-slate-editor] p {
  margin: 4px 0 !important;
  padding-left: 4px !important;
}
::v-deep .w-e-image-container img {
  vertical-align: bottom;
  width: 100% !important;
  height: auto !important;
  max-width: 150px !important;
}
::v-deep .w-e-image-dragger {
  // 隐藏图片推拽
  display: none;
}
::v-deep .w-e-selected-image-container {
  // 图片点击选中
  border: 1px solid #b4d5ff !important;
  padding: 1px !important;
  overflow: inherit !important;
}
::v-deep .w-e-image-container:hover {
  // 图片hover
  box-shadow: none !important;
}
</style>
<style lang="scss" scoped>
.footer-send-input {
  flex: 1;
  max-width: 100%;
  overflow-y: auto;
  word-break: break-all;
  display: flex;
  flex-direction: column;
  .send-btn {
    display: flex;
    justify-content: flex-end;
    margin-top: 6px;
    .explain-text {
      font-size: 10px;
      color: #bfbfbf;
      line-height: 32px;
      margin-right: 16px;
    }
  }
}
</style>
